<template>
  <tm-app>
    <tm-navbar title="我的" color="indigo" :hideHome="true"> </tm-navbar>
    <tm-sheet :margin="[30]" :padding="[30]" :round="3">
      <view class="flex flex-row flex-row-center-between mb-n10">
        <tm-avatar
          :size="150"
          :round="26"
          :img="userStore.userInfo.userHead || 'https://picsum.photos/200/300'"
        ></tm-avatar>
        <tm-sheet
          class="flex-1"
          :margin="[0, 0]"
          :padding="[0, 0]"
          _class="ml-n7"
        >
          <view class="flex flex-row flex-row-center-between bt-n2">
            <tm-text
              :font-size="40"
              color="#666666"
              class="font-weight-b"
              :label="userStore.userInfo.userName || '微信用户'"
            ></tm-text>
            <tm-icon
              _class="pa-n0"
              :fontSize="50"
              v-if="userStore.token"
              :followTheme="true"
              customicon
              @click="navigatTo('setting')"
              name="tmicon-cog"
            ></tm-icon>
          </view>
          <view class="flex flex-row flex-row-center-between mt-n2">
            <view class="flex flex-row">
              <tm-tag
                size="s"
                :margin="[0, 0]"
                :padding="[0]"
                :fontSize="20"
                :label="state.type[userStore.userInfo.userLevel]"
                v-if="userStore.token"
              ></tm-tag>
              <tm-tag
                size="s"
                :margin="[10, 0, 0, 0]"
                :padding="[0]"
                :fontSize="20"
                label="提升连接收益"
                @click="joinUs"
              ></tm-tag>
            </view>
            <tm-text
              v-if="userStore.token"
              :font-size="24"
              color="#666666"
              :label="`ID:${userStore.userInfo.id}`"
            ></tm-text>
          </view>
        </tm-sheet>
      </view>
      <tm-row :column="3" :gutter="5">
        <tm-col :height="0" @click="navigatTo('withDrawRecords')">
          <tm-text
            :fontSize="44"
            _class="font-weight-b"
            :label="getShowPrice(userStore.userInfo.userAccumulative)"
          >
          </tm-text>
          <tm-text
            :fontSize="24"
            label="累计提现 (元)"
            color="#666"
            _class="mt-n3"
          ></tm-text>
        </tm-col>
        <tm-col
          @click="navigatTo('withDraw')"
          :margin="[4, 0]"
          :height="0"
          borderColor="#999"
          :borderGutter="[1, 0, 1, 0]"
        >
          <tm-text
            :fontSize="44"
            _class="font-weight-b"
            :label="getShowPrice(userStore.userInfo.userBalance)"
          >
          </tm-text>
          <tm-text
            :fontSize="24"
            label="可提现 (元)"
            color="#666"
            _class="mt-n3"
          ></tm-text>
        </tm-col>
        <tm-col :height="0">
          <tm-text
            :fontSize="44"
            _class="font-weight-b"
            :label="getShowPrice(userStore.userInfo.connectionIncome)"
          >
          </tm-text>
          <tm-text
            label="连接收益 (元/次)"
            color="#666"
            :fontSize="24"
            _class="mt-n3"
          ></tm-text>
        </tm-col>
      </tm-row>
    </tm-sheet>

    <tm-sheet
      :follow-theme="true"
      :margin="[30, 0, 30, 30]"
      :round="4"
      @click="navigatTo('dev-next')"
      v-if="userStore.token"
      _class="flex flex-row flex-row-center-between"
    >
      <view class="flex flex-col flex-col-center-between">
        <tm-text :font-size="32" _class="text-weight-b">邀请入驻 >>></tm-text>
        <tm-text _class="mt-n5" :font-size="28"
          >免费生成属于你的专属邀请码</tm-text
        >
      </view>
      <tm-icon
        name="tmicon-md-planet"
        _class="mr-n10"
        :font-size="60"
      ></tm-icon>
    </tm-sheet>

    <tm-sheet :margin="[30, 0, 30, 0]" :padding="[30]" :round="3">
      <tm-cell
        :margin="[0, 0]"
        :titleFontSize="30"
        :title="item.name"
        showAvatar
        v-for="item in state.menus"
        :key="item.name"
        :avatarRound="0"
        :avatarSize="40"
        :avatar="item.icon"
        @click="navigatTo(item.page)"
      >
      </tm-cell>

      <tm-cell
        :margin="[0, 0]"
        :titleFontSize="30"
        title="在线客服"
        showAvatar
        :avatarRound="0"
        :avatarSize="40"
        openType="contact"
        avatar="/static/my/kf.png"
      >
        <template v-slot:title>
          <tm-button
            :width="state.contactBtnWidth"
            _class="flex-start"
            :margin="[0]"
            transprent
            text
            :fontSize="28"
            openType="contact"
            :shadow="0"
            size="small"
            fontColor="#333"
            label="在线客服"
          ></tm-button>
        </template>
      </tm-cell>
    </tm-sheet>
    <tm-button
      :margin="[30]"
      :round="10"
      block
      :loading="state.loading"
      label="block"
      @click="userHandltLogin"
    >
      {{ btnTitle }}
    </tm-button>
    <tm-message ref="msg"></tm-message>

    <tm-overlay v-model:show="state.showInvite" contentAnimation>
      <view @click.stop="">
        <tm-sheet
          :width="400"
          :height="120"
          :round="4"
          _class="flex flex-col flex-col-center-center"
        >
          <tm-text :fontSize="40" _class="text-weight-b" :label="getModalTitle">
          </tm-text>
          <tm-button
            :label="getBtnLabel"
            size="large"
            :loading="state.loading"
            _class="fulled"
            @click="userHandltLogin"
          ></tm-button>
        </tm-sheet>
      </view>
    </tm-overlay>
  </tm-app>
</template>

<script setup>
import { reactive, computed, ref } from "vue";
import { useUserStore } from "@/store";
import { appletDecodeOpenIdApi } from "@/api";
import { onLoad, onShow } from "@dcloudio/uni-app";

const userStore = useUserStore();

const getShowPrice = computed(() => (price) =>
  userStore.token ? price || 0 : "**.**"
);

const getBtnLabel = computed(() => {
  const userLevel = state.userLoginExtendForm.userLevel;
  if (["marketing", "sign"].includes(userLevel)) {
    return "登录助力";
  }
  return "接受邀请";
});

const getModalTitle = computed(() => {
  const userLevel = state.userLoginExtendForm.userLevel;
  if (userLevel == "marketing") {
    return "帮好友助力";
  }
  if (userLevel == "sign") {
    return "签到赚现金";
  }
  return state.type[userLevel];
});

const btnTitle = computed(() => (userStore.token ? "退出登录" : "授权登陆"));

const msg = ref(null);
const state = reactive({
  contactBtnWidth: 0,
  type: {
    HHR: "城市合伙人",
    TZ: "团长",
    TZY: "拓展员",
    SJ: "商家",
    YH: "普通用户",
    ZDL: "总代理",
  },
  menus: [
    {
      name: "我的家族",
      icon: "/static/my/jz.png",
      page: "wdjz",
    },
    {
      name: "收益记录",
      icon: "/static/my/sy.png",
      page: "syjl",
    },
    {
      name: "购物清单",
      icon: "/static/my/qd.png",
      page: "gwqd",
    },
    {
      name: "帮助文档",
      icon: "/static/my/bz.png",
      page: "bzwd",
    },
    {
      name: "我的优惠券",
      icon: "/static/my/yhj.png",
      page: "wdyhj",
    },
    {
      name: "我的套餐",
      icon: "/static/my/tc.png",
      page: "wdtc",
    },
  ],
  // 如下参数 直接打开小程序不用传，扫码注册的时候需要把二维码上参数带过来
  userLoginExtendForm: {
    userSuperId: "", //上级id
    userLevel: "", //注册级别
    showProportion: "", //分润比例
  },
  loading: false,

  showInvite: false,
});

onShow(() => {
  userStore.getUserInfo();
});

onLoad((params) => {
  if (params.scene) {
    const truthParams = decodeURIComponent(params.scene);
    // 依次对应，级别，分润比例，上级id
    const paramsArray = truthParams.split("@");
    state.userLoginExtendForm.userSuperId = paramsArray[2];
    state.userLoginExtendForm.showProportion = paramsArray[1];
    state.userLoginExtendForm.userLevel = paramsArray[0];
    state.showInvite = true;
    console.log("邀请注册", truthParams, state);
  }
  const { torpx, getWindow } = uni.$tm.u;
  state.contactBtnWidth = torpx(getWindow().width - 48 - 32 - 25 - 40);
  console.log(state.contactBtnWidth);
});

const navigatTo = (page) => {
  if (!userStore.token) {
    msg.value.show({ model: "error", text: "请先授权登录" });
    return;
  }
  uni.navigateTo({
    url: "/myPages/" + page,
  });
};

const userHandltLogin = () => {
  if (userStore.token) {
    userStore.userLoginOut();
    return;
  }
  state.loading = true;
  uni.login({
    provider: "weixin",
    success: async ({ code }) => {
      const { openid } = await appletDecodeOpenIdApi({ code });
      const registerByScanCode = Object.keys(state.userLoginExtendForm).every(
        (key) => state.userLoginExtendForm[key]
      );
      let apiForm = {
        openId: openid || "0c3mo1100rWSIP11n8100WXnhz0mo118",
        // openId: "0c3mo1100rWSIP11n8100WXnhz0mo118",
      };
      if (registerByScanCode) {
        apiForm = Object.assign({}, apiForm, state.userLoginExtendForm);
      }
      await userStore.userLogin(apiForm);
      state.loading = false;
      state.showInvite = false;
      const { userLevel, showProportion } = state.userLoginExtendForm;
      // 如果是活动助力
      if (["marketing", "sign"].includes(userLevel)) {
        msg.value.show({ model: "success", text: "助力成功" });
      } else {
        msg.value.show({ model: "success", text: "登陆成功" });
      }
    },
  });
};

const joinUs = () => {
  uni.navigateTo({
    url: "/homePages/joinUs?type=1",
  });
};
</script>

<style scoped></style>
